# -*- coding: utf-8 -*-

#
# fusion.http.Group
#
# Copyright 2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Harri Hämäläinen <hhamalai@iki.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import cgi, simplejson
from fusion.db.exceptions import Unauthorized
from fusion.db.profile import Profile
from fusion.http.FusionApp import FusionApp, Response
from fusion.http.Domain import Domain
from fusion.http.util import escape_html
from string import Template

T_profile = Template('''
    <h2>${name}</h2>

    <div class="picture">
    ${profile_pic}
    </div>

    ${pending_invitation}
    <!--<div>
    Wiki
    </div>-->
    <div>
    <div style="float:left;position:top;">${memberlist}</div>
    <div style="float:left;position:top;padding-left:10%;">${datasets}</div>
    </div>
    <!--${buttons}-->
''')

class Group(Domain):
    def do_GET(self):
        patterns = {
            '/': self.redirect_to,
            '/content': self.get,
            '/group': self.output_profile,
            '/members': self.output_list_members,
            '/remove_role': self.output_remove_role,
        }
        
        return self.match_response(patterns)

    def do_POST(self):
        form = self.read_request_form()
        
        if form.getvalue("add_role"):
            new_role = form.getvalue('role_to_add')
            member = form.getvalue('member')
            try:
                roles = self.db.get_roles(self.iid, member)
            except ValueError:
                pass
            else:
                if len(new_role) > 0:
                    roles.append(new_role)
                    self.db.set_roles(self.iid, member, roles)
            response = Response(301)
            response.add_header('Location', self.request_url())
            return response
        
        elif form.getvalue('remove_role'):
            role_to_remove = form.getvalue('role_to_remove')
            member = form.getvalue('member')
            try:
                roles = list(set(self.db.get_roles(self.iid, member)) - set([role_to_remove]))
            except ValueError:
                pass
            else:
                self.db.set_roles(self.iid, member, roles)
            response = Response(301)
            response.add_header('Location', self.request_url(path=False)+'/members')
            return response
        
        elif form.getvalue('get_invitation'):
            result = self.invitation(form)
            if result:
                return result
            else:
                return self.do_GET()
            
        elif form.getvalue('accept_invitation'):
            iid = form.getvalue('iid')
            self.accept_invitation(iid)
            return self.do_GET()

        elif form.getvalue('decline_invitation'):
            iid = form.getvalue('iid')
            self.decline_invitation(iid)
            return self.do_GET()
        
        elif form.getvalue('get_invitation'):
            result = self.invitation(form)
            if result:
                return result
            else:
                return self.do_GET()
        
        
    def active_roles_for(self, member, is_admin):
        roles = self.db.get_roles(self.iid, member)
        role_list = []
        for role in roles:
            remove_option = ''
            if is_admin:
                remove_option = '<a href="/remove_role?role=%s&member=%s">remove</a>' % (role, member)
            role_list.append('''<li>%s %s</li>''' % (role, remove_option))
        return '<ul>%s</ul>' % ''.join(role_list)
    
    def redirect_to(self):
        response = Response(status=301)
        response.add_header('Location', '/group/')
        return response
    
    def short_memberlist(self):
        members = self.db.list_members(self.iid)
        profile = Profile()
        member_list = []
        for member in members:
            profile.read(self.db, member)
            name = escape_html(profile.name) or member
            row = '<li><a href="http://%s.hexlabel.net">%s</a></li>' % (member, name) 
            member_list.append(row)
        
        return '<h3>Members</h3><ul>%s</ul>' % ''.join(member_list)
    
    
    def output_edit_profile(self):
        profile_pic = '''<img src="static/dummy.png" /><br />
                        <input type="file" name="profile_picture" />
                        <br />Delete picture
                        <input type="checkbox" name="remove_pic" />'''
                        
        if self.db.get(self.iid, 'info/pic.png'):
            profile_pic = '''<img src="content/info/pic.png" /><br />
                            <input type="file" name="profile_picture" />
                            <br />Delete picture
                            <input type="checkbox" name="remove_pic" />'''
            
        profile_values = {
          'name': escape_html(self.db.get(self.iid, 'info/name.txt') or self.iid),
          'pending_invitation': self.pending_invitation(self.environ),
          'memberlist': self.short_memberlist(),
          'datasets': self.domain_datasets(),
          'profile_pic': profile_pic,
          'buttons': '<a href="?edit=True">Save</a>',
        }
        
        return self.create_page('Group',
                                T_profile.safe_substitute(profile_values).encode('utf-8'), 
                                style='profile')
    
    
    def output_view_profile(self):
        profile_pic = '<img src="static/dummy.png" />'
        if self.db.get(self.iid, 'info/pic.png'):
            profile_pic = '<img src="content/info/pic.png" />'
            
        
        profile_values = { 
          'name': escape_html(self.db.get(self.iid, 'info/name.txt') or self.iid),
          'pending_invitation': self.pending_invitation(self.environ),
          'memberlist': self.short_memberlist(),
          'datasets': self.domain_datasets(),
          'profile_pic': profile_pic,
          'buttons': '<a href="?edit=True">Edit</a>',
        }
        
        return self.create_page('Group',
                                T_profile.safe_substitute(profile_values).encode('utf-8'),
                                style='profile')
    
    def output_list_members(self):
        members = self.db.list_members(self.iid)
        T_add_role = Template('''<form action="" method="post">
            <input type="text" name="role_to_add" />
            <input type="hidden" name="member" value="${iid}" />
            <input type="submit" name="add_role" value="Add role" />
            </form>''')
        T_row = Template('''
            <tr style="background-color: ${cycled_color}"><td>
            <a href="http://${iid}.hexlabel.net">${name}</a>
            </td><td>
            ${roles}
            ${add_role}
            </td></tr>
        ''')
        
        is_admin = 'admin' in self.db.get_roles(self.iid, self.db.get_my_iid())
        rows = []
        profile = Profile()
        color = ''
        for member in members:
            if color:
                color = ''
            else:
                color = '#eee'
            profile.read(self.db, member)
            rows.append(T_row.substitute({
                'iid': member, 
                'name': escape_html(profile.name),
                'roles': self.active_roles_for(member, is_admin),
                'cycled_color': color,
                'add_role': T_add_role.substitute({'iid': member}) if is_admin else ''
            }))
        content = '<table>%s</table>' % ''.join(rows)
        response = Response()
        response.add_header('Content-Type', 'text/html;charset=utf-8')
        response.append_output(self.create_page('Members', content.encode('utf-8')))
        return response
    
    
    def output_remove_role(self):
        member = ''.join((self.querydict.get('member') or [])[:1])
        role = ''.join((self.querydict.get('role') or [])[:1])
        profile = Profile()
        profile.read(self.db, member)
        content = Template('''You are going to remove role "${role}" from 
                     <a href="http://${iid}.hexlabel.net">${name}</a>.
                     <form action="" method="post">
                     <input type="hidden" name="role_to_remove" value="${role}" />
                     <input type="hidden" name="member" value="${iid}" />
                     <input type="submit" name="remove_role" value="Confirm" />
                     </form>
                  ''').substitute({'iid': member, 
                                   'name': escape_html(profile.name) or member, 
                                   'role': role})
        response = Response()
        response.add_header('Content-Type', 'text/html;charset=utf-8')
        response.append_output(self.create_page('Remove role', content.encode('utf-8')))
        return response
    
